<template>
  <div class="workflow-designer">
    <!-- 步骤导航 -->
    <div class="steps-container">
      <el-steps :active="currentStep" align-center finish-status="success">
        <el-step
          v-for="(step, index) in steps"
          :key="index"
          :title="step.title"
          :status="getStepStatus(index)"
          @click="handleStepChange(index)"
          class="step-item"
        />
      </el-steps>

      <!-- 进度指示器 -->
      <div class="progress-indicator">
        <!-- <div class="progress-info"> -->
          <!-- <span class="current-step">步骤 {{ currentStep + 1 }} / {{ steps.length }}</span> -->
          <!-- <span class="step-title">{{ steps[currentStep].title }}</span> -->
        <!-- </div> -->
        <el-progress
          :percentage="progressPercentage"
          :stroke-width="6"
          :show-text="false"
          class="progress-bar"
        />
      </div>
    </div>

    <!-- 内容区域 -->
    <div class="content-container">
      <el-card class="content-card">
        <template #header>
          <div class="card-header">
            <h2 class="module-title">{{ steps[currentStep].title }}</h2>
            <div class="module-actions">
              <el-button v-if="currentStep > 0" @click="handlePrevious" :icon="ArrowLeft">
                上一步
              </el-button>
              <el-button
                v-if="currentStep < steps.length - 1"
                type="primary"
                @click="handleNext"
                :disabled="!isCurrentStepValid"
                :icon="ArrowRight"
              >
                下一步
              </el-button>
              <el-button
                v-if="currentStep === steps.length - 1"
                type="success"
                @click="handleExport"
                :icon="Download"
                :disabled="!isAllStepsValid"
              >
                打印配置
              </el-button>
            </div>
          </div>
        </template>

        <!-- 动态内容区域 -->
        <div class="module-content">
          <component
            :is="currentComponent"
            v-model="currentStepData"
            @validate="handleStepValidation"
            :api-config="currentStep === 2 ? apiConfig : undefined"
            :form-config="currentStep === 2 ? formConfig : undefined"
            :ref="getComponentRef"
          />
        </div>
      </el-card>
    </div>

    <!-- 底部操作栏 -->
    <!--<div class="footer-actions">
       <div class="action-left">
        <el-button @click="handleReset" :icon="Refresh"> 重置配置 </el-button>
      </div> -->
      <!-- <div class="action-right">
        <el-button-group>
          <el-button v-if="currentStep > 0" @click="handlePrevious" :icon="ArrowLeft">
            上一步
          </el-button>
          <el-button
            v-if="currentStep < steps.length - 1"
            type="primary"
            @click="handleNext"
            :disabled="!isCurrentStepValid"
            :icon="ArrowRight"
          >
            下一步
          </el-button>
        </el-button-group>
      </div> 
    </div>-->
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowLeft, ArrowRight, Download } from '@element-plus/icons-vue'
import BasicInfoSimple from '/@/components/BasicInfo/BasicInfoSimple.vue'
import FormDesigner from '/@/components/FormDesigner/FormDesigner.vue'
import FlowDesigner from '/@/components/FlowDesigner/FlowDesigner.vue'
import type { WorkflowConfiguration, FlowConfig } from '/@/views/workflow/types/index'
import type { BasicInfo } from '/@/components/BasicInfo/types/index'
import type { FormConfig } from '/@/components/FormDesigner/types/index'
// 导入API函数
import { workflowApi } from '/@/api/workflow/flowDesigner/index'

// 组件引用
const currentComponentRef = ref(null)
const flowDesignerRef = ref(null)
const formDesignerRef = ref(null)
const basicInfoRef = ref(null)

// Props and Emits
interface Props {
  initialConfig?: WorkflowConfiguration
  initialStep?: number
  initialStepValidation?: boolean[]
}

interface Emits {
  (e: 'update:config', value: WorkflowConfiguration): void
  (e: 'update:step', value: number): void
  (e: 'update:step-validation', value: boolean[]): void
  (e: 'export', value: WorkflowConfiguration): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 响应式状态
const currentStep = ref(props.initialStep ?? 0)
const stepValidation = ref<boolean[]>(props.initialStepValidation ?? [false, false, true])

// 本地状态管理，替代store
const basicInfo = ref<BasicInfo>({
  name: '',
  description: '',
})
const formConfig = ref<FormConfig>({
  fields: [],
  layout: {
    columns: 1,
    labelWidth: '120px',
    size: 'default' as const,
  },
  validation: {
    rules: {},
  },
})
const flowConfig = ref<FlowConfig>({
  nodeName: '开始',
  error: false,
  type: 0,
  priorityLevel: '',
  settype: '',
  selectMode: '',
  selectRange: '',
  directorLevel: '',
  noHanderAction: '',
  examineEndDirectorLevel: '',
  ccSelfSelectFlag: '',
  conditionList: [],
  nodeUserList: [],
  childNode: null,
  conditionNodes: [],
})

// 初始化数据
if (props.initialConfig) {
  basicInfo.value = { ...props.initialConfig.basicInfo }
  formConfig.value = { ...props.initialConfig.formConfig }
  flowConfig.value = { ...props.initialConfig.flowConfig }
  stepValidation.value = props.initialStepValidation ?? [false, false, true]
}

// 步骤配置
const steps = [
  {
    title: '基本信息',
    description: '配置工作流基本信息',
    component: 'BasicInfoSimple',
  },
  {
    title: '表单设计',
    description: '设计动态表单',
    component: 'FormDesigner',
  },
  {
    title: '流程设计',
    description: '设计工作流程',
    component: 'FlowDesigner',
  },
]

// API配置
const apiConfig = {
  // getRoles,
  // getDepartments,
  // getEmployees,
  // getConditions,
  getRoles: workflowApi().getRoles,
  getDepartments: workflowApi().getDepartments,
  getEmployees: workflowApi().getEmployees,
  getConditions: workflowApi().getConditions,
  validateExpression: workflowApi().validateExpression,

}

// 组件映射
const componentMap = {
  BasicInfoSimple,
  FormDesigner,
  FlowDesigner,
}

// 计算属性
const currentComponent = computed(() => {
  const componentName = steps[currentStep.value].component
  return componentMap[componentName as keyof typeof componentMap]
})

const currentStepData = computed({
  get() {
    switch (currentStep.value) {
      case 0:
        return basicInfo.value
      case 1:
        return formConfig.value
      case 2:
        return flowConfig.value
      default:
        return {}
    }
  },
  set(value) {
    switch (currentStep.value) {
      case 0:
        basicInfo.value = value
        break
      case 1:
        formConfig.value = value
        break
      case 2:
        flowConfig.value = value
        break
    }
    // 触发配置更新事件
    emitConfigUpdate()
  },
})

const progressPercentage = computed(() => {
  return Math.round(((currentStep.value + 1) / steps.length) * 100)
})

const isCurrentStepValid = computed(() => {
  // console.log(stepValidation.value)
  return stepValidation.value[currentStep.value] || false
})

const isAllStepsValid = computed(() => {
  // console.log(stepValidation.value)
  return stepValidation.value.every((valid) => valid)
})

// 方法
const getStepStatus = (index: number) => {
  if (index < currentStep.value) {
    return stepValidation.value[index] ? 'finish' : 'error'
  } else if (index === currentStep.value) {
    return 'process'
  } else {
    return 'wait'
  }
}

// 获取组件引用的函数
const getComponentRef = (el: any) => {
  currentComponentRef.value = el
  // 根据当前步骤设置对应的组件引用
  switch (currentStep.value) {
    case 0:
      basicInfoRef.value = el
      break
    case 1:
      formDesignerRef.value = el
      break
    case 2:
      flowDesignerRef.value = el
      break
  }
}


const handleStepChange = (step: number) => {
  // 只允许向前跳转到已完成的步骤或下一步
  if (step <= currentStep.value || (step === currentStep.value + 1 && isCurrentStepValid.value)) {
    currentStep.value = step
    emit('update:step', step)
  } else {
    ElMessage.warning('请先完成当前步骤')
  }
}

const handleNext = () => {
  if (isCurrentStepValid.value && currentStep.value < steps.length - 1) {
    currentStep.value++
    emit('update:step', currentStep.value)
  }
}

const handlePrevious = () => {
  if (currentStep.value > 0) {
    currentStep.value--
    emit('update:step', currentStep.value)
  }
}

const handleStepValidation = (isValid: boolean) => {
  stepValidation.value[currentStep.value] = isValid
  emit('update:step-validation', [...stepValidation.value])
}

const configValid = () => {
  console.log(flowDesignerRef.value)
  // 检查所有步骤是否有效
  if (!isAllStepsValid.value) {
    ElMessage.error('请完成所有步骤后再导出')
    return false
  }

  // 如果flowDesignerRef不存在或者validate验证不通过
  if (flowDesignerRef.value && !flowDesignerRef.value.validate()) {
    ElMessage.error('请先完成流程设计步骤')
    return false
  }

  // 如果当前在流程设计步骤，需要额外验证FlowDesigner
  // if (currentStep.value === 2 && flowDesignerRef.value) {
  //   const flowDesignerValid = flowDesignerRef.value.validate()
  //   if (!flowDesignerValid) {
  //     ElMessage.error('流程设计配置有误，请检查后再导出')
  //     return false
  //   }
  // }
  return true
}

const handleExport = () => {
  // 检查所有步骤是否有效
  if (!configValid()) {
    return
  }
  
  // 所有验证通过，导出配置
  const config = exportConfiguration()
  emit('export', config)
  ElMessage.success('配置已导出')
}

const handleReset = async () => {
  try {
    await ElMessageBox.confirm('确定要重置所有配置吗？此操作不可撤销。', '确认重置', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    // 重置所有配置
    basicInfo.value = {
      name: '',
      description: '',
    }
    formConfig.value = {
      fields: [],
      layout: {
        columns: 1,
        labelWidth: '120px',
        size: 'default',
      },
      validation: {
        rules: {},
      },
    }
    flowConfig.value = {
      nodeName: '发起人',
      error: false,
      type: 0,
      priorityLevel: '',
      settype: '',
      selectMode: '',
      selectRange: '',
      directorLevel: '',
      noHanderAction: '',
      examineEndDirectorLevel: '',
      ccSelfSelectFlag: '',
      conditionList: [],
      nodeUserList: [],
      childNode: null,
      conditionNodes: [],
    }
    currentStep.value = 0
    stepValidation.value = [false, false, true]

    // 触发配置更新事件
    emitConfigUpdate()
    emit('update:step', 0)
    emit('update:step-validation', [...stepValidation.value])

    ElMessage.success('配置已重置')
  } catch {
    // 用户取消操作
  }
}

// 导出配置
const exportConfiguration = (): WorkflowConfiguration => {
  return {
    id: props.initialConfig?.id || 0,
    basicInfo: basicInfo.value,
    formConfig: formConfig.value,
    flowConfig: flowConfig.value,
    metadata: {
      version: '1.0.0',
      exportTime: new Date().toISOString(),
    },
  }
}

// 配置更新事件
const emitConfigUpdate = () => {
  emit('update:config', exportConfiguration())
}

// 监听配置变化，触发更新事件
watch(
  [basicInfo, formConfig, flowConfig],
  () => {
    emitConfigUpdate()
  },
  { deep: true },
)

// 暴露方法给父组件
defineExpose({
  // 验证配置
  validate: () => {
    return configValid()
  },
})
</script>

<style scoped>
/* 使用深度选择器覆盖el-step__icon-inner样式 */
:deep(.el-step__icon-inner) {
  font-size: 14px !important; /* 您想要的字体大小 */
  font-weight: 500 !important; /* 您想要的字体粗细 */
  /* 添加其他您需要的样式 */
}
.workflow-designer {
  max-width: 1200px;
  width: 100%;
  margin: 0 auto;
  padding: 0 16px;
}

.steps-container {
  background: #fff;
  padding: 5px 24px 10px;
  border-radius: 8px;
  margin-bottom: 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.step-item {
  cursor: pointer;
  transition: all 0.3s ease;
}

.step-item:hover {
  opacity: 0.8;
}

.progress-indicator {
  /* margin-top: 24px; */
  padding-top: 16px;
  /* border-top: 1px solid #e4e7ed; */
}

.progress-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.current-step {
  font-size: 14px;
  color: #909399;
}

.step-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.progress-bar {
  width: 100%;
}

.content-container {
  min-height: 600px;
}

.content-card {
  min-height: 600px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.module-title {
  margin: 0;
  color: #303133;
  font-size: 18px;
  font-weight: 500;
}

.module-actions {
  display: flex;
  gap: 8px;
}

.module-content {
  /* padding: 24px 0; */
  min-height: 500px;
}

.placeholder-content {
  text-align: center;
  padding: 60px 24px;
}

.placeholder-content h3 {
  color: #303133;
  margin-bottom: 16px;
  font-size: 20px;
}

.placeholder-content p {
  color: #606266;
  margin-bottom: 32px;
  font-size: 16px;
}

.footer-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 0;
  margin-top: 24px;
  border-top: 1px solid #e4e7ed;
}

.action-left,
.action-right {
  display: flex;
  gap: 8px;
}

@media (max-width: 768px) {
  .workflow-designer {
    padding: 0 8px;
  }

  .steps-container {
    padding: 16px;
  }

  .card-header {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }

  .module-actions {
    width: 100%;
    justify-content: flex-end;
  }

  .footer-actions {
    flex-direction: column;
    gap: 16px;
  }

  .action-left,
  .action-right {
    width: 100%;
    justify-content: center;
  }
}
</style>
